package com.eryos.android.cigarettecounter;

/**
 * Project :  CigaretteCounter
 * Author :   Olivier Combe 
 * URL :      http://eryos.fr/CigaretteCounter/
 *
 * Copyright (C) 2011 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

//import android.os.Bundle;
//import android.view.View;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.eryos.android.cigarettecounter.beans.SmokeTime;
import com.eryos.android.cigarettecounter.io.Preferences;

public class CigaretteCounter extends RootActivity {

	/** *************** Static Variables *************** **/	
	private final static String TAB 		= "     ";
	private final static String NA_LABEL 	= "NA";
	
    /** *************** Instance Variables *************** **/	
//	private String monthValueLabel ;
//    private String weekValueLabel ;

    private float cigarettePrice = 0;

    /** *************** UI Elements *************** **/
    private TextView dailyCountValue;
    private TextView delayValue;
    private TextView lastCigValue;
    private TextView avgWeekValue;
    private TextView avgMonthValue;
	
    private Button addCigaretteButton; 
    private Button showWeeklyStatButton; 
    private Button showMonthlyStatButton; 
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Listeners & Handlers 
        addCigaretteButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	clickAddButton();
            }
        });
        
        showWeeklyStatButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Log.d(getLocalClassName(), "Click Weekly Stats Button");
            	//launchWeeklyStats();
            	showView(VIEW.WEEKLY);
            }
        });
        
        showMonthlyStatButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Log.d(getLocalClassName(), "Click Monthly Stats Button");
            	//launchMonthlyStats();
            	showView(VIEW.MONTHLY);
            }
        });
    }
    
    /**
     * init Values ( not UI ) for this activiry
     */
    public void initValues(){
    	/* Retrieve the Cigarette price */
    	Preferences pref = new Preferences(getSharedPreferences(PREFS_NAME, 0));
    	pref.readParamFromFile();
    	cigarettePrice = pref.getCigarettePrice();
    	
//    	monthValueLabel = new String(avgMonthValue.getText()+"");
//    	weekValueLabel = new String(avgWeekValue.getText()+"");

    	/* Refresh the UI with DB values */
    	showDetails();
    	
        hideWaitingMessage();
    }
    
    /**
     * Method used to refresh the Daily Counter  
     */
    public void showDailyCount(){    	
    	String currentValue = TAB+db.getDailyCount()+" "+getResources().getString(R.string.cigarette);
    	
    	dailyCountValue.setText(currentValue);
    }
    
    /**
     * Method used to refresh the Weekly Average  
     */
    public void showWeeklyAverage(){
    	double weekAvg = db.getWeeklyAverage();
    	
    	String weekValueLabel = getResources().getString(R.string.home_avg_week_value).replaceAll("#", weekAvg+"");
    	if ( weekAvg <= 0 )
    		avgWeekValue.setText(TAB+NA_LABEL);
    	else
    		avgWeekValue.setText(TAB+weekAvg);
    }
    
    /**
     * Method used to refresh the Monthly Average  
     */
    public void showMonthlyAverage(){
    	double monthAvg = db.getMonthlyAverage();
    	
    	String monthValueLabel = getResources().getString(R.string.home_avg_month_value).replaceAll("#", monthAvg+"");
    	if ( monthAvg <= 0 )
    		avgMonthValue.setText(TAB+NA_LABEL);
    	else
    		avgMonthValue.setText(TAB+monthValueLabel);
    }
    
    /**
     * Method used to refresh the Delay since Last Cigarette  
     */
    public void showDelaySinceLast(){
    	SmokeTime last = db.getDelaySinceLast();
    	
    	String lastLabel = "" ;
    	if ( last.getHour() == 0 )
    		lastLabel = getResources().getString(R.string.home_delay_last_value_short);
    	else
    		lastLabel = getResources().getString(R.string.home_delay_last_value);

    	lastLabel = lastLabel.replaceAll("#1", last.getHour()+"").replaceAll("#2", last.getMinute()+"").replaceAll("#3", last.getTotalMinutes()+"");
    	
    	if ( last != null && last.getTotalMinutes() < 0 )
    		lastCigValue.setText(TAB+NA_LABEL);
    	else
    		lastCigValue.setText(TAB+lastLabel);
    }
    
    /**
     * Method used to refresh the Average delay between 2 cigarettes  
     */
    public void showAverageDelay(){
    	SmokeTime delay = db.getAverageDelay();
    	
    	String delayLabel = "";
    	if ( delay.getHour() == 0 )
    		delayLabel = getResources().getString(R.string.home_average_delay_value_short);
    	else
    		delayLabel = getResources().getString(R.string.home_average_delay_value);

    	delayLabel = delayLabel.replaceAll("#1", delay.getHour()+"").replaceAll("#2", delay.getMinute()+"").replaceAll("#3", delay.getTotalMinutes()+"");

    	if ( delay != null && delay.getTotalMinutes() <= 0 )
    		delayValue.setText(TAB+NA_LABEL);
    	else
    		delayValue.setText(TAB+delayLabel);
    }
    
    /**
     * Init all UI elements
     */
    public void initUI(){
        setContentView(R.layout.main);

        addCigaretteButton 		= (Button) findViewById(R.id.home_add_cigarette_button);
        showWeeklyStatButton 	= (Button) findViewById(R.id.home_button_history_week); 
        showMonthlyStatButton 	= (Button) findViewById(R.id.home_button_history_month);
        
        dailyCountValue = (TextView) findViewById(R.id.home_daily_count_value_field);
        delayValue 		= (TextView) findViewById(R.id.home_average_delay_value_field);
        lastCigValue 	= (TextView) findViewById(R.id.home_delay_last_value_field);
        avgWeekValue	= (TextView) findViewById(R.id.home_week_average_value_field);
        avgMonthValue	= (TextView) findViewById(R.id.home_month_average_value_field);
    }    
    
    /**
     * Method used to show/refresh all values on Main View
     */
    public void showDetails(){
    	showDailyCount();
    	
    	showDelaySinceLast();
    	
    	showAverageDelay();
    	
    	showWeeklyAverage();
    	
    	showMonthlyAverage();
    }
        
    /**
     * Method called when a click is made on the "+1 button"
     */
    public void clickAddButton(){
    	Log.d(getLocalClassName(), "Click on Add Button");
    	db.insertCurrentTimestamp("", cigarettePrice);

    	showDetails();
    	
    	Toast.makeText(this, R.string.home_insert_OK, Toast.LENGTH_SHORT).show();
    }
}
